@using Hsp.WebNovels.Model.Dtos
@using Hsp.WebNovels.Model.Models
@model Content

@{
    //ViewBag.Title = "章节内容管理";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="row-fluid" id="content-wrapper">

    <!-- 中间内容展示区域 -->
        @await Component.InvokeAsync("PageHeader")

        <div id="toolbar">
            <div class="form-inline" role="form">
                <form class="form-inline form-toolbar">
                    <div class="form-group row">
                        <input name="search" class="form-control form-control-sm" type="text" placeholder="搜索">
                    </div>
                </form>
                <button id="remove" class="btn btn-sm btn-danger" disabled>
                    <i class="glyphicon glyphicon-remove"></i>批量删除
                </button>
                <button id="btnAdd" class="btn btn-sm btn-primary">
                    <i class="glyphicon glyphicon-plus"></i>添加章节内容
                </button>
                @await Html.PartialAsync("~/Views/Shared/Buttons/_ToolbarQueryGroupWithExport.cshtml")
            </div>
        </div>

        <table id="content-table" class="table table-bordered table-striped table-sm table-hover" data-toggle="table" data-toolbar="#toolbar"></table>

    </div>

</div>

<!-- 章节内容编辑模态窗体 //-->
<div class="modal fade" id="editModel" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false" aria-labelledby="editModelLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editModelLabel">章节内容编辑</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

                <form class="form-horizontal">
                    <input type="hidden" id="txtChapterId" name="txtChapterId" />
                    <input type="hidden" id="txtNovelId" name="txtNovelId" />
                    <div class="form-group row">
                        <label for="txtContents" class="col-2 col-form-label col-form-label-sm">章节内容</label>
                        <div class="col-10">
                            <textarea id="txtContents" name="txtContents" class="form-control form-control-sm"></textarea>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label asp-for="txtContents" class="col-2 col-form-label col-form-label-sm">章节内容</label>
                        <div class="col-10">
                            <textarea asp-for="txtContents" name="txtContents" class="form-control form-control-sm"></textarea>
                            <span asp-validation-for="txtContents" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="txtCreateTime" class="col-2 col-form-label col-form-label-sm">添加时间</label>
                        <div class="col-10">
                            <input id="txtCreateTime" name="txtCreateTime" type="text" class="form-control form-control-sm" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="txtUpdateTime" class="col-2 col-form-label col-form-label-sm">更新时间</label>
                        <div class="col-10">
                            <input id="txtUpdateTime" name="txtUpdateTime" type="text" class="form-control form-control-sm" />
                        </div>
                    </div>

                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">
                    <i class="glyphicon glyphicon-floppy-remove" aria-hidden="true"></i>关闭
                </button>
                <button type="button" class="btn btn-sm btn-primary" id="btnSave">
                    <i class="glyphicon glyphicon-floppy-saved" aria-hidden="true"></i>保存
                </button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

    <link href="~/css/tablelist.css" rel="stylesheet" />
    <link href="~/css/task.css" rel="stylesheet" />

<style type="text/css">
        td {
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            word-break: keep-all;
        }
</style>

    <script type="text/javascript">

        var $table = $('#content-table'),
            $remove = $('#remove'),
            selections = [],
            key = 'ChapterId';

        var pageNumber = 1, pageSize = 10;
        var pageListUrl = "/Contents//PageList";

        $(function () {

            $table = $('#content-table'),
                $remove = $('#remove');

            $("#btnAdd").click(function () {

                // 默认Guid类型字段初始化处理

                $("#editModelLabel").html("章节内容信息添加");
                $('#editModel').modal('toggle');
            });

            initTable();

            // 关键词查询
            $('input[name="search"]').bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    pageNumber = 1;
                    refreshTable();
                }
            });

            	    // 查询按钮点击事件
                        $('#btnSearch').unbind('click').bind('click', function () {
                            pageNumber = 1;
                            refreshTable();
                        });

        });

        // 刷新表格数据
        function refreshTable() {
            $table.bootstrapTable({ url: pageListUrl });
            $table.bootstrapTable('refresh', { pageNumber: 1 });
        }

        // 初始化表
        function initTable() {

            //先销毁表格
            $table.bootstrapTable('destroy');

            $table.bootstrapTable({
                height: getHeight(),
                method: 'get', // 请求方式（*）
                dataType: "json", // 数据类型
                url: pageListUrl, // 请求后台地址,
                toolbar: '#toolbar', //工具按钮用哪个容器
                striped: true, // 使表格带有条纹
                uniqueId: key, // 唯一标识
                idField: key, // 标识哪个字段为id主键
                pagination: true, // 在表格底部显示分页工具栏
                pageSize: pageSize, // 分页大小
                pageNumber: pageNumber, // 当前页码
                pageList: [10, 20, 50, 100, 200, 500],
                sidePagination: "server", //表格分页的位置
                //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
                //设置为limit可以获取limit, offset, search, sort, order
                queryParamsType: "undefined",
                queryParams: function queryParams(params) { //设置查询参数
                    var param = {
                        pageNumber: params.pageNumber,
                        pageSize: params.pageSize,
                        title: $("input[name='search']").val()
                    };
                    pageNumber = params.pageNumber;
                    return param;
                },
                columns: [
                    [
                        {
                            field: 'checked',
                            checkbox: true
                        }, {
                            title: '序号',
                            field: 'RowNumber',
                            width: 60,
                            align: 'center',
                            formatter: function (value, row, index) {
                            	var options = $table.bootstrapTable('getOptions');
                            	return options.pageSize * (options.pageNumber - 1) + index + 1;
                            }
                        }, {
                            field: 'Contents',
                            title: '章节内容',
                            width: 60,
                            halign: 'center',
                            align: 'center',
                        }, {
                            field: 'CreateTime',
                            title: '添加时间',
                            width: 105,
                            halign: 'center',
                            align: 'center',
                            formatter: function (value, row, index) {
                                return (value == null || value.length == 0) ? "" : value.toDateTimeString();
                            }
                        }, {
                            field: 'UpdateTime',
                            title: '更新时间',
                            width: 105,
                            halign: 'center',
                            align: 'center',
                            formatter: function (value, row, index) {
                                return (value == null || value.length == 0) ? "" : value.toDateTimeString();
                            }
                        }, {
                            title: '操作',
                            width: 90,
                            halign: 'center',
                            align: 'center',
                            events: operateEvents,
                            formatter: operateFormatter
                        }
                    ]
                ],
                formatLoadingMessage: function () {
                    return "请稍等，正在加载中...";
                },
                formatNoMatches: function () { //没有匹配的结果
                    return '无符合条件的记录';
                }
            });

            // sometimes footer render error.

            setTimeout(function () {
                $table.bootstrapTable('resetView');
                $('[data-toggle="tooltip"]').tooltip();
            }, 200);

            $table.on('check.bs.table uncheck.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
                    $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);

                    // save your data, here just save the current page

                    selections = getIdSelections();

                    // push or splice the selections if you want to save all data selections

                });

            $remove.click(function () { // 批量删除
                var ids = getIdSelections();
                $remove.prop('disabled', true);
                BatchDelete(ids.toString()); // 批量删除
            });

            $(window).resize(function () {
                $table.bootstrapTable('resetView', {
                    height: getHeight()
                });
            });
        }

        // 获取选择项
        function getIdSelections() {
            return $.map($table.bootstrapTable('getSelections'), function (row) {
                return row[key];
            });
        }

        // 操作内容格式化
        function operateFormatter(value, row, index) {
            var edit = ['<a class="edit" href="javascript:void(0)" title="修改章节内容">',
                '<i class="glyphicon glyphicon-edit"></i>',
                '</a>'];

            var remove = ['<a class="remove" href="javascript:void(0)" title="删除章节内容">',
                '<i class="glyphicon glyphicon-remove"></i>',
                '</a>'];
            edit = edit.concat(remove);
            return edit.join('');
        }

        // 操作事件响应
        window.operateEvents = {
            'click .edit': function (e, value, row, index) {
                //alert('You click edit action, row: ' + JSON.stringify(row));

                //debugger;
                //console.info("编辑前获取行数据：");
                console.info(row);

                $("#txtChapterId").val(row.ChapterId); // 章节ID
                $("#txtNovelId").val(row.NovelId); // 小说ID
                $("#txtContents").val(row.Contents); // 章节内容
                $("#txtCreateTime").val(row.CreateTime); // 添加时间
                $("#txtUpdateTime").val(row.UpdateTime); // 更新时间

                $("#editModelLabel").html("章节内容信息修改");
                $('#editModel').modal('toggle');
            },
		'click .remove': function (e, value, row, index) {
			Delete(row[key]); // 删除行数据
			}
		};

        // 获取内容高度
        function getHeight() {
            var heightCorrection = 115;
            return $(window).height() - $('h2').outerHeight(true) - heightCorrection;
        }

/// <summary>
/// 物理删除数据
/// </summary>

function Delete(id) {
	if (confirm("您确定要删除该章节内容吗？")) {
		$.ajax({
			type: "POST",
			url: "/Contents//Delete/" + id + "?rnd=" + (Math.random() * 10),
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (rst) {
				//console.info(rst);
				if (rst && rst.success) {
					refreshTable();
					modals.info(rst.Message ?? rst.message);
				} else {
					modals.error(rst.Message ?? rst.message);
				}
			}
		});
	}
}

/// <summary>
/// 批量物理删除
/// </summary>

function BatchDelete(ids) {
	if (confirm("您确定要批量删除这些章节内容吗？")) {
		$.ajax({
			type: "POST",
			url: "/Contents//BatchDelete/" + ids + "?rnd=" + (Math.random() * 10),
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (rst) {
				//console.info(rst);
				if (rst && rst.success) {
					refreshTable();
					modals.info(rst.Message ?? rst.message);
				} else {
					modals.error(rst.Message ?? rst.message);
				}
			}
		});
	}
}

        $(function () {

            $('#editModel').on('hidden.bs.modal', function () { // 关闭模态窗体事件
                $("#editModel form")[0].reset();
                $("#btnSave").prop("disabled", false); // 解除保存按钮禁用
                $("#editModel form input[type='hidden']").val("");
            });

             // 数据保存
            $("#btnSave").unbind("click").bind("click", function () {

                var txtChapterId = $("#txtChapterId").val(); // 章节ID
                var txtNovelId = $("#txtNovelId").val(); // 小说ID
                var txtContents = $("#txtContents").val(); // 章节内容
                var txtCreateTime = $("#txtCreateTime").val(); // 添加时间
                var txtUpdateTime = $("#txtUpdateTime").val(); // 更新时间


$("#btnSave").prop("disabled", "disabled"); // 禁用保存按钮，防止重复提交


                // 字符串输入超长处理
                if (txtChapterId && txtChapterId.length > 36) {
                    toastr.error('章节ID超过设定长度36！');
                    $("#txtChapterId").focus();
                    return;
                }
                if (txtNovelId && txtNovelId.length > 36) {
                    toastr.error('小说ID超过设定长度36！');
                    $("#txtNovelId").focus();
                    return;
                }

                // 字符串中异常字符处理
                if (txtChapterId != undefined && txtChapterId.length > 0) {
                    txtChapterId = txtChapterId.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 章节ID
                }
                if (txtNovelId != undefined && txtNovelId.length > 0) {
                    txtNovelId = txtNovelId.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 小说ID
                }
                if (txtContents != undefined && txtContents.length > 0) {
                    txtContents = txtContents.replace(/'|\\|\"|\||>|<|\*|\?/g, ""); // 章节内容
                }

                var obj = {};
                obj.ChapterId = txtChapterId; // 章节ID
                obj.NovelId = txtNovelId; // 小说ID
                obj.Contents = txtContents; // 章节内容
                obj.CreateTime = txtCreateTime; // 添加时间
                obj.UpdateTime = txtUpdateTime; // 更新时间

                //console.info("保存提交前数据：");
                console.info(JSON.stringify(obj));

                $.ajax({
                    type: "POST",
                    url: "/Contents//Save/?rnd=" + (Math.random() * 10),
                    data: JSON.stringify(obj),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (rst) {
                        console.info(rst);
                        if (rst && rst.success) {
            
                            refreshTable();
            
                            $("#editModel").modal("hide");
            
                            $("#btnSave").prop("disabled", "");
                        } else {
                            $.alert({title: "错误提示!", content: rst.Message });
                        }
                    }
                });
            });

        });

    </script>

}

